package com.xmh.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.VideoAttributes;
import lombok.extern.slf4j.Slf4j;

/**
 * 视频转码工具类
 * 
 * @author pc
 *
 */
@Slf4j
public class VideoTranscodingUtil {

	public static InputStream toMp4(InputStream inputStream, String fileName) {
		if (inputStream == null) {
			throw new RuntimeException("参数 inputStream 为空");
		}
		String objectKey = System.currentTimeMillis() + "_" + fileName;

		File source = new File("upload\\" + objectKey);

		/*
		 * msmpeg4v2
		 * libx264
		 * libx264rgb
		 * h264
		 */
		String codec = "msmpeg4v2";
		String suffix = "mp4";
		
		File target = new File("upload\\" + objectKey + "Target." + suffix);

		if (!source.exists()) {
			source.getParentFile().mkdirs();
			try {
				source.createNewFile();
			} catch (IOException e) {
				log.error("创建文件报错--------", e);
				return null;
			}
		}

		try {
			FileUtils.copyInputStreamToFile(inputStream, source);
		} catch (IOException e) {
			log.error("文件复制报错--------", e);
			return null;
		}

		VideoAttributes video = new VideoAttributes();
		video.setCodec(codec);
		video.setBitRate(160000);
		video.setFrameRate(15);
//			video.setSize(new VideoSize(400, 300));
		EncodingAttributes attrs = new EncodingAttributes();
		attrs.setFormat(suffix);
		attrs.setVideoAttributes(video);
		Encoder encoder = new Encoder();

		try {
			encoder.encode(source, target, attrs);
		} catch (IllegalArgumentException | EncoderException e) {
			log.error("视频转码失败--------", e);
			return null;
		}

		try {
			return new FileInputStream(target);
		} catch (FileNotFoundException e) {
			log.error("返回视频inputStream失败--------", e);
			return null;
		} finally {
			target.delete();
		}
	}

}
